package com.herui.iot.ui.evaluation.execute;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.herui.device_lib.listener.DeviceLis;
import com.herui.device_lib.listener.DeviceLisAdapter;
import com.herui.sdyu_lib.http.callback.Callback;
import com.herui.sdyu_lib.utils.StringUtils;
import com.herui.sdyu_lib.utils.ToastUtil;
import com.herui.sport_care.BaseView;
import com.herui.sport_care.data.RepositoryFactory;
import com.herui.sport_care.data.check.BetaDataFileUploadRequest;
import com.herui.sport_care.data.check.EvaluationStage;
import com.herui.sport_care.data.check.source.CheckSource;
import com.herui.sport_care.data.eval.EvalInfo;
import com.protontek.healthy.sdkcore.sphygmomanometer.api.BPDataBean;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by amanda.shan on 2022/12/1.
 */
public class QuietCheckPresenter extends BaseExecutePresenter {

    static String TAG = "QuietCheckPresenter";

    public static interface View extends BaseView, DeviceLis {
        // 检测倒计时
        default void onCheckSecond(long second) {
        }

        // 心率回调
        default void onHeart(int heart, int maxHeart, int minHeart) {
        }

        // 上传成功
        default void onSucess() {
        }
    }

    ExecutorService executorService = Executors.newSingleThreadExecutor();

    CheckSource checkSource;
    View view;

    private Timer timer;
    private Long startTime;

    public QuietCheckPresenter(View view, EvalInfo evalInfo) {
        super(evalInfo);
        this.view = view;
        checkSource = RepositoryFactory.getInstance().getCheckSource();
    }

    @Override
    public void start() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (stage != null) {
                    view.onCheckSecond((System.currentTimeMillis() - startTime) / 1000);
                    if (evalUserInfo != null && evalInfo != null) {
                        quiteDataUp(false);
                    }
                }
            }
        }, 0, 1000);

        DeviceLisAdapter.add(deviceLis);
    }

    public void startCheck() {
        startTime = System.currentTimeMillis();
        stage = EvaluationStage.QUIESCENT;
    }

    public void stop() {
        if (timer != null) {
            timer.cancel();
        }
        DeviceLisAdapter.remove(deviceLis);
        devicePresenter.disConnectAll();
    }

    public Long getCheckDuration() {
        if (startTime == null) {
            return null;
        }
        return (System.currentTimeMillis() - startTime) / 1000;
    }

    @Override
    public BaseView getView() {
        return view;
    }

    // 完成检测
    public void finish() {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                Long evaluationSchemeId = evalInfo.getEvaluationSchemeId();
                try {
                    sportFileManager.saveHeart(evalUserInfo.getUserId().intValue(),
                            evaluationSchemeId.intValue(), hearts);
                } catch (IOException e) {
                    e.printStackTrace();
                    ToastUtil.showMessage("保存心率数据失败");
                    return;
                }

                try {
                    sportFileManager.closeEcgStore();
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }

                String ecgPath = sportFileManager.uploadEcg(evalUserInfo.getUserId().intValue(),
                        evaluationSchemeId.intValue(), EvaluationStage.QUIESCENT);
                if (StringUtils.isEmpty(ecgPath)) {
                    ToastUtil.showMessage("上传心电数据失败");
                    return;
                }
                String heartPath = sportFileManager.uploadHeart(evalUserInfo.getUserId().intValue(),
                        evaluationSchemeId.intValue());
                if (StringUtils.isEmpty(heartPath)) {
                    ToastUtil.showMessage("上传心率数据失败");
                    return;
                }

                // 上传文件路径
                BetaDataFileUploadRequest betaDataFileUploadRequest =
                        new BetaDataFileUploadRequest();
                betaDataFileUploadRequest.setBeEvaluatedId(evalUserInfo.getUserId());
                betaDataFileUploadRequest.setEvaluationSchemeId(evaluationSchemeId);
                betaDataFileUploadRequest.setQuiescentEcgFileUrl(ecgPath);
                betaDataFileUploadRequest.setQuiescentHeartRateTrendFileUrl(heartPath);
                checkSource.fileDataUpload(betaDataFileUploadRequest,
                        new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        Log.d(TAG,
                                "onSuccess: 上传文件路径成功" + JSON.toJSONString(betaDataFileUploadRequest));
                        quiteDataUp(true);
                    }

                    @Override
                    public void onError(Throwable e, String code, String message) {
                        processError(e, code, message);
                    }
                });
            }
        });
    }

    @Override
    protected void dataUploadSucess(Boolean uploadAll) {
        if (uploadAll) {
            view.onSucess();
        }
    }

    protected DeviceLis deviceLis = new DeviceLis() {

        @Override
        public void onConnectEcg(boolean flag) {
            handler.post(() -> {
                view.onConnectEcg(flag);
            });
        }

        @Override
        public void onConnectSpo(boolean flag) {
            handler.post(() -> {
                view.onConnectSpo(flag);
            });
        }

        @Override
        public void onBpResult(BPDataBean bpDataBean) {
            handler.post(() -> {
                baseDeviceLis.onBpResult(bpDataBean);
                view.onBpResult(bpDataBean);
            });
        }

        @Override
        public void onReceiveSpO2(int spo) {
            handler.post(() -> {
                baseDeviceLis.onReceiveSpO2(spo);
                view.onReceiveSpO2(spo);
            });
        }

        @Override
        public void onEcgHeart(int heart) {
            handler.post(() -> {
                baseDeviceLis.onEcgHeart(heart);
                view.onHeart(heart, maxHeart, minHeart);
            });
        }

        @Override
        public void onEcgData(byte[] bytes) {
            handler.post(() -> {
                baseDeviceLis.onEcgData(bytes);
                view.onEcgData(bytes);
            });
        }
    };


}
